package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"news/cache"
	"news/models"
)

type NewsController struct {
	beego.Controller
}

func (c *NewsController) Create() {
	title := c.GetString("title")
	address := c.GetString("address")
	img := c.GetString("img")
	classify := c.GetString("classify")
	name := c.GetString("name")
	time := c.GetString("time")
	zt := c.GetString("zt")

	if title == "" || address == "" || img == "" || classify == "" || name == "" || time == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "数据不能为空",
		}
		c.ServeJSON()
		return
	}

	var news models.News
	news.Title = title
	news.Address = address
	news.Img = img
	news.Classify = classify
	news.Name = name
	news.Time = time
	news.Zt = zt

	key := fmt.Sprintf("news_create_%d", news.ID)
	jsonData, _ := json.Marshal(key)
	cache.Rdb.Set(cache.Ctx, key, jsonData, 0)

	if err := news.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "系统错误",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}
func (c *NewsController) Del() {

	id, _ := c.GetInt("id")
	var news models.News
	news.ID = uint(id)

	key := fmt.Sprintf("news_del_%d", news.ID)
	cache.Rdb.Del(cache.Ctx, key)

	if err := news.Del(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "系统错误",
		}
		c.ServeJSON()
		return
	}

	if news.Zt == "已发布" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "已发布不能删除",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
func (c *NewsController) List() {
	var err error
	var news []models.News
	err = models.DB.Find(&news).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "查询失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "查询相关",
			"data": news,
		}
		c.ServeJSON()
		return
	}
}
